import React from 'react'
import '../../assets/css/home/detail.less'
import {PullToRefresh, Carousel, WingBlank, Toast, Modal} from "antd-mobile";

export default class DetailComponent extends React.Component {
    constructor() {
        super()
        this.state = {
            navCheck: 0,
            uid:0,
            gid: '143208071',
            goodData: [],
            goodColor:[],
            goodSize:[],
            goodColorValues:[],
            goodSizeValues:[],
            images: [],
            page:1,
            com:[],
            pushCom:[],
            moreCom:[],
            refreshing:false,
            modal:false,
            sizeId:0,
            colorId:0,
            sizeVal:'',
            colorVal:'',
            count:1,
            cart:[],
            show:false
        }
    }

    componentWillMount() {
        if (this.props.history.location.query !== undefined) {
            this.setState({
                gid: this.props.history.location.query.id
            })
        }
        if(localStorage['uid']){
            this.setState({
                uid:localStorage['uid']
            })
        }
        if(localStorage['cart']){
            let cart = JSON.parse(localStorage['cart'])
            if(cart.length>0){
                this.setState({
                    show:true
                })
            }
        }
    }
   

    componentDidMount() {
        this.getData()
        this.getCom(1)
        this.getDataInfo()
    }
    // 商品详情
    getData() {
        fetch(
            'http://vueshop.glbuys.com/api/home/goods/info?gid=' + this.state.gid + '&type=details&token=1ec949a15fb709370f'
        )
            .then((res) => {
                return res.json()
            })
            .then((res) => {
                if (res.code === 200) {
                    this.setState({
                        goodData: res.data,
                        images: res.data.images
                    }, () => {
                        console.log(this.state.goodData, this.state.images);
                    })
                }
            })
    }
    //商品规格
    getDataInfo(){
        fetch(
            'http://vueshop.glbuys.com/api/home/goods/info?gid='+this.state.gid+'&type=spec&token=1ec949a15fb709370f'
        )
            .then((res) => {
                return res.json()
            })
            .then((res) => {
                if (res.code === 200) {
                    this.setState({
                        goodColor:res.data[0],
                        goodSize:res.data[1],
                        goodColorValues:res.data[0].values,
                        goodSizeValues:res.data[1].values
                    }, () => {
                        console.log(res)
                    })
                }
            })
    }
    // 评论
    getCom(page){
        fetch(
            'http://vueshop.glbuys.com/api/home/reviews/index?gid='+this.state.gid+'&token=1ec949a15fb709370f&page='+page+''
        )
            .then((res) => {
                return res.json()
            })
            .then((res) => {
                if (res.code === 200) {
                    if(page===1){
                        this.setState({
                            com:res.data
                        }, () => {
                            // console.log(this.state.com);
                        })
                    }else{
                        this.setState({
                            pushCom:res.data
                        }, () => {
                                console.log('111', this.state.page);
                                if (this.state.pushCom) {
                                    for (var i = 0; i <this.state.pushCom.length ; i++) {
                                        this.state.moreCom.push(this.state.pushCom[i])
                                    }
                                    console.log(this.state.moreCom);
                                }
                                this.setState({
                                    refreshing: false
                                })
                            // console.log(this.state.pushCom);
                        })
                    }

                }
            })
    }
    // nav切换
    navCheck(index) {
        if (index === this.state.navCheck) {
            return
        }
        if(index===2){
            this.setState({
                moreCom:this.state.com
            })
        }
        this.setState({
            navCheck: index
        })
    }

    goBack() {
        this.props.history.goBack()
    }
    // 上拉加载
    up(){
        console.log('加载');
        this.setState({
            page:this.state.page+1,
            refreshing: true,
            pushCom:[]
        })
        setTimeout(() => {
            this.setState({ refreshing: false });
        }, 3000);
        this.getCom(this.state.page)



    }
    // 收藏
    collect(){
        var tf = JSON.stringify(localStorage['login'])

        if(!tf){
            this.props.history.push('/login')
            return
        }
        fetch(
            'http://vueshop.glbuys.com/api/goods/fav?uid='+this.state.uid+'&gid='+this.state.gid+'&token=1ec949a15fb709370f'
        )
            .then((res) => {
                return res.json()
            })
            .then((res) => {
                if (res.code === 200) {
                    Toast.info('收藏成功', 1,null,false);
                }else if(res.code===302){
                    Toast.info('已经收藏过此物品', 1,null,false);
                }
            })
    }
    // 加购
    addSub(e){
        this.showModal(e)
    }
    onClose(){
        this.setState({
            modal: false,
        });
    }
    checkSize(item){
        if(this.state.sizeId===item.vid){
            this.setState({
                sizeId:0,
                sizeVal:0
            })
        }else{
            this.setState({
                sizeId:item.vid,
                sizeVal:item.value
            })
        }
    }
    checkColor(item){
        if(this.state.colorId===item.vid){
            this.setState({
                colorId:0,
                colorVal:0
            })
        }else{
            this.setState({
                colorId:item.vid,
                colorVal:item.value
            })
        }
    }

    showModal(e){
        e.preventDefault(); // 修复 Android 上点击穿透
        this.setState({
            modal: true,
        });
    }
    add(){
        this.setState({
            count:this.state.count+1
        })
    }
    sub(){
        if(this.state.count===1){
            return
        }
        this.setState({
            count:this.state.count-1
        })
    }
    //加入购物车选择规格确定事件
    submitCart(){
        if(this.state.colorId===0){
            Toast.info('请选择'+this.state.goodColor.title, 1,null,false);
            return
        }
        if(this.state.sizeId===0){
            Toast.info('请选择'+this.state.goodSize.title, 1,null,false);
            return
        }
        Toast.info('添加成功', 1,null,false);
        if(localStorage['cart']){
            console.log('有');
            this.setState({
                cart:JSON.parse(localStorage['cart'])
            },()=>{
                if(this.state.cart.length===0){
                    console.log('cart没东西');
                    console.log('state.cart',this.state.cart);
                }else{
                    for (var i = 0; i <this.state.cart.length ; i++) {
                        if(this.state.cart[i].data.gid ===this.state.goodData.gid){
                            console.log('gid相同');
                            if(this.state.cart[i].color.value===this.state.colorVal&&this.state.cart[i].size.value===this.state.sizeVal){
                                console.log('一模一样');
                                this.state.cart[i].count =  this.state.cart[i].count+1
                                this.setState({
                                    cart:this.state.cart
                                },()=>{
                                    localStorage.setItem('cart', JSON.stringify(this.state.cart))
                                    console.log(JSON.parse(localStorage['cart']));
                                })
                                return
                            }
                        }
                    }
                }
                this.addCart()
            })
        }else{
            this.addCart()
        }
        this.onClose()
    }



    //满足加入购物车条件时
    addCart() {
        this.setState({
            show:true
        })
        var arr = {
            data: this.state.goodData,
            color: {title: this.state.goodColor.title, value: this.state.colorVal},
            size: {title: this.state.goodSize.title, value: this.state.sizeVal},
            count:this.state.count,
            check:true
        }
        this.state.cart.unshift(arr)
        this.setState({
            cart:this.state.cart
        },()=>{
            localStorage.setItem('cart', JSON.stringify(this.state.cart))
            console.log(this.state.cart);
            console.log(JSON.parse(localStorage['cart']));
        })

    }
    render() {
        
        return (
            <div id='detail'>
                <div className='header'>
                    <div onClick={this.goBack.bind(this)}><img src="/images/user/my/返回.png" alt=""/></div>
                    <div style={this.state.navCheck === 0 ? {borderBottom: '2px solid orange'} : {}}
                         onClick={this.navCheck.bind(this, 0)}>商品
                    </div>
                    <div style={this.state.navCheck === 1 ? {borderBottom: '2px solid orange'} : {}}
                         onClick={this.navCheck.bind(this, 1)}>详情
                    </div>
                    <div style={this.state.navCheck === 2 ? {borderBottom: '2px solid orange'} : {}}
                         onClick={this.navCheck.bind(this, 2)}>评价
                    </div>
                    <div 
                        style={{position:'relative'}}
                    onClick={()=>{
                        localStorage.setItem('selectedTab', JSON.stringify('cart'))
                        this.props.history.push('/')
                    }}>
                        
                        <div style={this.state.show?{
                            width:'8px',height:'8px',background:'red',
                            borderRadius:'50%',position:'absolute',top:'10px',right:'0px'}:{display:'none'}}>
                        </div>
                        <img src="/images/home/goods/cart.png" alt=""/></div>
                </div>
                <div className='header-div'></div>
                <div style={this.state.navCheck === 0 ? {} : {display: 'none'}}>
                    <div className='swiper'>
                        <WingBlank style={{width: '100%', padding: '0px', margin: '0px'}}>
                            <Carousel
                                autoplayInterval={4000}
                                autoplay={true}
                                infinite={true}
                                dots={true}
                                beforeChange={(from, to) => {
                                }
                                }
                                // afterChange={}
                            >
                                {this.state.images.map((item, index) => (
                                    <img
                                        key={index}
                                        src={item}
                                        alt=""
                                        style={{width: '100%', verticalAlign: 'top', height: 400}}
                                        onLoad={() => {

                                        }}
                                    />
                                ))}
                            </Carousel>
                        </WingBlank>
                    </div>
                    <div className='good-info'>
                        <div>{this.state.goodData.title}</div>
                        <div>￥{this.state.goodData.price}</div>
                        <div>
                            <div>快递: {this.state.goodData.freight}元</div>
                            <div>月销量{this.state.goodData.sales}件</div>
                        </div>
                    </div>
                    <div className='com'>
                        <div>
                            商品评价
                        </div>
                        {this.state.com?
                            <div>
                                {this.state.com.map((item,index)=>{
                                    return(
                                        <div key={index} className='user-com'>
                                            <div>
                                                <div><img src={item.head} alt=""/></div>
                                                <div>{item.nickname}</div>
                                            </div>
                                            <div>{item.content}</div>
                                            <div>{item.times}</div>
                                        </div>
                                    )
                                })}
                                <div className='more'>
                                    <div onClick={()=>{
                                        this.setState({
                                            navCheck:2,
                                            moreCom:this.state.com
                                        })
                                    }}>查看更多评价</div>
                                </div>
                            </div> :
                            <div className='no-com'>暂无评论！</div>
                        }

                    </div>
                    <div className='footer'>
                        <div onClick={this.collect.bind(this)}>收藏</div>
                        <div onClick={this.addSub.bind(this)}>加入购物车</div>
                    </div>
                </div>
                <div style={this.state.navCheck===1?{}:{display:'none'}}>
                    <div style={{fontSize:'16px'}} className="detailImgWrap" dangerouslySetInnerHTML={{__html:this.state.goodData.bodys}}></div>
                </div>
                {this.state.navCheck===2?
                <div className='com moreCom'>
                    <div>
                        商品评价
                    </div>
                        {this.state.moreCom?
                            <PullToRefresh
                                damping={60}
                                style={{
                                    overflow: 'auto',
                                    textAlign:'center',
                                    height:'calc(100vh - 51px)'
                                }}
                                direction='up'
                                refreshing={this.state.refreshing}
                                onRefresh={this.up.bind(this)}
                            >
                            <div style={{
                                textAlign:'left'
                            }}>
                                {this.state.moreCom.map((item,index)=>{
                                    return(
                                        <div key={index} className='user-com'>
                                            <div>
                                                <div><img src={item.head} alt=""/></div>
                                                <div>{item.nickname}</div>
                                            </div>
                                            <div>{item.content}</div>
                                            <div>{item.times}</div>
                                        </div>
                                    )
                                })}
                            </div>
                            </PullToRefresh>:
                            <div className='no-com'>暂无评论！</div>
                        }
                </div>:''
                }

                <Modal
                    popup
                    visible={this.state.modal}
                    onClose={this.onClose.bind(this)}
                    animationType="slide-up"
                    afterClose={() => { ;}}
                >
                    <div className='info-header' style={{
                        padding:'10px 0 0 10px',
                        display:'flex',
                        color:'black',
                        alignItems: 'center',
                        borderBottom: '1px solid rgba(169,169,169,.4)'
                    }}>
                        <div style={{width:'40px',height:'40px',marginRight:'15px'}}><img style={{width:'100%',height:'100%'}} src={this.state.images[0]} alt=""/>
                        </div>
                        <div style={{width:'90%'}}>
                            <div style={{width:'90%',textAlign:'left',fontSize:'12px',paddingRight:'20px'}}>{this.state.goodData.title}</div>
                            <div style={{
                                display:'flex',
                                justifyContent: 'space-between'
                            }}>
                                <div style={{color:'red'}}>￥{this.state.goodData.price}</div>
                                <div style={{color:'rgba(169,169,169)',fontSize:'12px',paddingRight:'10px'}}>商品编码:{this.state.goodData.gid}</div>
                            </div>
                        </div>
                    </div>
                    <div style={{padding:'10px',textAlign:'left',color:'black'}}>
                        <div style={{marginBottom:'10px'}}>{this.state.goodColor.title}</div>
                        <div style={{display:'flex',marginBottom:'20px'}}>
                            {this.state.goodColorValues.map((item,index)=>{
                                return(
                                    <div key={index} style={this.state.colorId ===item.vid?{
                                        padding:'3px 5px',
                                        background:'#FDA208',
                                        marginLeft:'8px',
                                        borderRadius: '5px',
                                        color:'white'
                                    }:{   padding:'3px 5px',
                                        background:'#EFEFEF',
                                        marginLeft:'8px',
                                        borderRadius: '5px'}} onClick={this.checkColor.bind(this,item)}
                                    >
                                        {item.value}
                                    </div>
                                )
                            })}
                        </div>
                        <div style={{marginBottom:'10px'}}>{this.state.goodSize.title}</div>
                        <div style={{display:'flex',marginBottom:'20px'}}>
                            {this.state.goodSizeValues.map((item,index)=>{
                                return(
                                    <div key={index} style={this.state.sizeId ===item.vid?{
                                        padding:'3px 5px',
                                        background:'#FDA208',
                                        marginLeft:'8px',
                                        borderRadius: '5px',
                                        color:'white'
                                    }:{ padding:'3px 5px',
                                        background:'#EFEFEF',
                                        marginLeft:'8px',
                                        borderRadius: '5px',}} onClick={this.checkSize.bind(this,item)}
                                    >
                                        {item.value}
                                    </div>
                                )
                            })}
                        </div>
                        <div style={{display:'flex',justifyContent: 'space-between',}}>
                            <div>购买数量</div>
                            <div style={{display:'flex',justifyContent: 'space-between',alignItems:' center',border:'1px solid black',borderRadius: '5px'}}>
                                <div onClick={this.sub.bind(this)} style={{padding:'5px 10px'}}>-</div>
                                <div style={{padding:'0px 10px',borderLeft:'1px solid black',
                                borderRight:'1px solid black'}}>{this.state.count}</div>
                                <div onClick={this.add.bind(this)} style={{padding:'5px 10px'}}>+</div>
                            </div>
                        </div>
                    </div>
                    <div style={{marginTop:'50px',lineHeight:'40px',color:'white',background:'red'}}  onClick={this.submitCart.bind(this)}>确定</div>
                </Modal>
            </div>
        )
    }
}